package cn.virde.example.javafx.asyn;

import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;

import java.net.URL;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ResourceBundle;

/**
 *  异步更新时间 Example
 */
public class AsynUpdateController implements Initializable {

    @FXML
    private Label timeLabel;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        final Thread thread = new Thread(new UpdateTask(timeLabel));
        thread.setDaemon(true);
        thread.start();
    }

    static class UpdateTask extends Task{
        private Label timeLabel;

        public UpdateTask(Label timeLabel) {
            this.timeLabel = timeLabel;
        }

        @Override
        protected Object call() throws Exception {
            while(true){
                System.out.println("run ... ");
                try {
                    Thread.sleep(1000);
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            timeLabel.setText(LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
